package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Class;
import com.EAsystem.entity.Major;
import com.EAsystem.service.ClassService;
import com.EAsystem.service.MajorService;
import com.EAsystem.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class ClassController {

    @Autowired
    private ClassService classService;

    @Autowired
    private MajorService majorService;

    @Autowired
    private StudentService studentService;

    // 班级信息管理页面, 处理列表, 搜索和分页
    @GetMapping("/class")
    public String listClasses(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "5") int size,
                              Model model,
                              @RequestParam(required = false) String className) {
        try {
            System.out.println("班级查询 - page: " + page + ", size: " + size + ", className: " + className);
            
            PageInfo<Class> pageInfo;
            if (className != null && !className.trim().isEmpty()) {
                System.out.println("执行班级名称查询，搜索条件: " + className.trim());
                pageInfo = classService.findByNamePage(className.trim(), page, size);
            } else {
                System.out.println("查询所有班级");
                pageInfo = classService.findAllByPage(page, size);
            }

            if (pageInfo == null) {
                pageInfo = new PageInfo<>();
            }

            System.out.println("查询结果 - 总记录数: " + pageInfo.getTotal() + ", 当前页记录数: " + pageInfo.getList().size());

            // 为每个班级计算学生数量
            if (pageInfo.getList() != null && !pageInfo.getList().isEmpty()) {
                for (Class clazz : pageInfo.getList()) {
                    try {
                        List<com.EAsystem.entity.Student> students = studentService.findByClassId(clazz.getId());
                        clazz.setStudentCount(students != null ? students.size() : 0);
                    } catch (Exception e) {
                        System.err.println("计算班级 " + clazz.getId() + " 的学生数量失败: " + e.getMessage());
                        clazz.setStudentCount(0);
                    }
                }
            }

            // 获取所有专业信息, 用于新增/编辑模态框的下拉选择
            List<Major> majorsList = majorService.findAll();
            model.addAttribute("majors", majorsList); // 修改为majors以匹配JSP

            model.addAttribute("classes", pageInfo.getList());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());
            model.addAttribute("nameSearch", className); // 保持与分页链接一致
            
        } catch (Exception e) {
            System.err.println("班级查询异常: " + e.getMessage());
            e.printStackTrace();
            
            // 设置错误时的默认值
            model.addAttribute("classes", new java.util.ArrayList<>());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", 0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("nameSearch", className);
            model.addAttribute("error", "查询班级信息失败：" + e.getMessage());
        }

        return "admin/class_info";
    }

    // 新增班级
    @PostMapping("/class/add")
    public String addClass(Class classObj, @RequestParam("majorId") Integer majorId) {
        try {
            System.out.println("=== 新增班级开始 ===");
            System.out.println("班级名称: " + classObj.getName());
            System.out.println("接收到的majorId: " + majorId);
            

            System.out.println("classService是否为null: " + (classService == null));
            System.out.println("majorService是否为null: " + (majorService == null));
            
            // 验证参数
            if (classObj.getName() == null || classObj.getName().trim().isEmpty()) {
                System.err.println("错误：班级名称为空");
                return "redirect:/admin/class?error=nameEmpty";
            }
            
            if (majorId == null) {
                System.err.println("错误：专业ID为空");
                return "redirect:/admin/class?error=majorEmpty";
            }
            
            // 验证专业是否存在
            try {
                Major existingMajor = majorService.findById(majorId);
                if (existingMajor == null) {
                    System.err.println("错误：专业ID " + majorId + " 不存在");
                    return "redirect:/admin/class?error=majorNotFound";
                }
                System.out.println("找到专业: " + existingMajor.getName());
            } catch (Exception e) {
                System.err.println("验证专业时发生异常: " + e.getMessage());
                e.printStackTrace();
                return "redirect:/admin/class?error=majorCheckFailed";
            }
            
            // 设置专业信息
            Major major = new Major();
            major.setId(majorId);
            classObj.setMajor(major);
            System.out.println("设置专业后的major: " + major.getId());
            
            // 打印即将保存的班级对象信息
            System.out.println("准备保存的班级对象:");
            System.out.println("  - 班级名称: " + classObj.getName());
            System.out.println("  - 专业ID: " + (classObj.getMajor() != null ? classObj.getMajor().getId() : "null"));
            System.out.println("  - 年级: " + classObj.getGrade());
            
            // 调用service保存
            System.out.println("准备调用classService.save()");
            boolean result = classService.save(classObj);
            System.out.println("保存结果: " + result);
            
            if (result) {
                System.out.println("=== 新增班级成功 ===");
                return "redirect:/admin/class?success=true";
            } else {
                System.err.println("=== 新增班级失败：没有插入任何记录 ===");
                return "redirect:/admin/class?error=saveFailed";
            }
            
        } catch (Exception e) {
            System.err.println("=== 新增班级异常 ===");
            System.err.println("异常类型: " + e.getClass().getName());
            System.err.println("异常消息: " + e.getMessage());
            e.printStackTrace();
            
            // 检查是否是数据库相关异常
            Throwable cause = e.getCause();
            while (cause != null) {
                System.err.println("根本异常: " + cause.getClass().getName() + " - " + cause.getMessage());
                cause = cause.getCause();
            }
            
            return "redirect:/admin/class?error=exception&msg=" + e.getMessage();
        }
    }

    // 编辑班级
    @PostMapping("/class/edit")
    public String editClass(Class classObj, @RequestParam("majorId") Integer majorId) {
        try {
            System.out.println("=== 编辑班级开始 ===");
            System.out.println("班级ID: " + classObj.getId());
            System.out.println("班级名称: " + classObj.getName());
            System.out.println("接收到的majorId: " + majorId);
            
            // 设置专业信息
            if (majorId != null) {
                Major major = new Major();
                major.setId(majorId);
                classObj.setMajor(major);
                System.out.println("设置专业后的major: " + major.getId());
            }
            
            // 调用service编辑（时间设置在service层处理）
            System.out.println("准备调用classService.edit()");
            boolean result = classService.edit(classObj);
            System.out.println("编辑结果: " + result);
            
            if (result) {
                System.out.println("=== 编辑班级成功 ===");
            } else {
                System.err.println("=== 编辑班级失败 ===");
            }
            
        } catch (Exception e) {
            System.err.println("=== 编辑班级异常 ===");
            System.err.println("异常类型: " + e.getClass().getName());
            System.err.println("异常消息: " + e.getMessage());
            e.printStackTrace();
        }
        return "redirect:/admin/class";
    }

    // 删除单个班级
    @GetMapping("/class/delete/{id}")
    public String deleteClass(@PathVariable Integer id) {
        classService.delete(id);
        return "redirect:/admin/class";
    }

    // 批量删除班级
    @GetMapping("/class/batchDelete")
    public String batchDeleteClasses(@RequestParam("ids") String ids) {
        List<Integer> idList = new ArrayList<>();
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    idList.add(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        if (!idList.isEmpty()) {
            classService.batchDelete(idList);
        }
        return "redirect:/admin/class";
    }

    // 获取单个班级信息（用于编辑模态框填充）
    @GetMapping("/class/view/{id}")
    @ResponseBody
    public java.util.Map<String, Object> viewClass(@PathVariable Integer id) {
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        try {
            Class clazz = classService.findById(id);
            if (clazz != null) {
                result.put("success", true);
                result.put("clazz", clazz);
            } else {
                result.put("success", false);
                result.put("message", "班级不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取班级信息失败：" + e.getMessage());
        }
        return result;
    }

    // 测试数据库连接方法
    @GetMapping("/class/test")
    @ResponseBody
    public String testDatabaseConnection() {
        try {
            System.out.println("=== 开始测试数据库连接 ===");
            
            // 测试专业查询
            List<Major> majors = majorService.findAll();
            System.out.println("专业总数: " + (majors != null ? majors.size() : "null"));
            
            if (majors != null && !majors.isEmpty()) {
                System.out.println("第一个专业: " + majors.get(0).getName());
                
                // 测试根据ID查询专业
                Major firstMajor = majorService.findById(majors.get(0).getId());
                System.out.println("根据ID查询专业结果: " + (firstMajor != null ? firstMajor.getName() : "null"));
            }
            
            // 测试班级查询
            PageInfo<Class> classPage = classService.findAllByPage(1, 5);
            System.out.println("班级总数: " + classPage.getTotal());
            
            return "数据库连接正常！专业数量: " + (majors != null ? majors.size() : "null") + ", 班级数量: " + classPage.getTotal();
            
        } catch (Exception e) {
            System.err.println("数据库连接测试失败: " + e.getMessage());
            e.printStackTrace();
            return "数据库连接失败: " + e.getMessage();
        }
    }

}